package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.GoodsStore;
import cn.wolfcode.car.business.domain.StockBill;
import cn.wolfcode.car.business.domain.StockBillItem;
import cn.wolfcode.car.business.mapper.GoodsStoreMapper;
import cn.wolfcode.car.business.mapper.StockBillItemMapper;
import cn.wolfcode.car.business.mapper.StockBillMapper;
import cn.wolfcode.car.business.query.StockBillQuery;
import cn.wolfcode.car.business.service.IStockBillService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class StockBillServiceImpl implements IStockBillService {
    @Autowired
    private StockBillMapper stockBillMapper;
    @Autowired
    private StockBillItemMapper stockBillItemMapper;
    @Autowired
    private GoodsStoreMapper goodsStoreMapper;


    @Override
    public TablePageInfo<StockBill> query(StockBillQuery query) {
        //使用paigeHelper插件
        PageHelper.startPage(query.getPageNum(),query.getPageSize());
        //将list集合传入到TablePageInfo进行封装
        List<StockBill> stockBills = stockBillMapper.selectForList(query);
        for (StockBill stockBill : stockBills) {
            int totalAmounts = 0;
            BigDecimal totalPrice=new BigDecimal("0");
            List<StockBillItem> stockBillItems =  stockBillItemMapper.selectByBillId(stockBill.getId());
            for (StockBillItem stockBillItem : stockBillItems) {
                totalAmounts += stockBillItem.getAmounts();
                totalPrice =  totalPrice.add(stockBillItem.getPrice().multiply(new BigDecimal(stockBillItem.getAmounts().toString())));
            }
            stockBill.setTotalAmounts(totalAmounts);
            stockBill.setTotalPrice(totalPrice);
        }
        return new TablePageInfo<StockBill>(stockBills);
    }



    @Override
    public void save(StockBill stockBill) {
        stockBillMapper.insert(stockBill);
    }

    @Override
    public void edit(StockBill stockBill) {
        stockBillMapper.updateByPrimaryKey(stockBill);
    }

    @Override
    public StockBill get(Long id) {
        return stockBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public StockBill selectByBillId(Long id) {
        StockBill StockBill = stockBillMapper.selectByBillId(id);
        return StockBill;
    }

    /**
     * 作废操作
     * @param id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        //根据传入的id查询到bill的数据
        StockBill stockBill = stockBillMapper.selectByPrimaryKey(id);
        //判断是否是作废状态
        if (StockBill.BILLSTATUS_CANCELLATION.equals(stockBill.getStatus())){
            //如果是作废状态则抛出异常
            throw new BusinessException("非法操作");
        }
        //根据bill的id查询到该条订单添加的商品有什么
        List<StockBillItem> stockBillItems = stockBillItemMapper.selectByBillId(id);
        //去仓库的中间表中查询是否存在这些物品
        for (StockBillItem stockBillItem : stockBillItems) {
            GoodsStore  goodsStore = goodsStoreMapper.selectByGoods(stockBillItem.getGoodsId(),stockBill.getStoreId());
            //如果商品不存在则不抛出异常 并且为入库操作
            if (goodsStore==null && stockBill.getType()==StockBill.PUTSTORE){
                throw new BusinessException("该仓库商品库存为空,非法操作");
            }
            //判断出入库  如果是入库
            if (stockBill.getType()==StockBill.PUTSTORE){
                if (goodsStore.getAmounts()<stockBillItem.getAmounts()){
                    throw new BusinessException("仓库库存不足,非法操作");
                }
                goodsStore.setAmounts(goodsStore.getAmounts()-stockBillItem.getAmounts());
                goodsStoreMapper.updateByPrimaryKey(goodsStore);
            }else {//出库的操作
                //判断是否有该商品在仓库中
                if (goodsStore==null){
                    GoodsStore newGoodsStore = new GoodsStore();
                    newGoodsStore.setStoreId(stockBill.getStoreId());
                    newGoodsStore.setGoodsId(stockBillItem.getGoodsId());
                    newGoodsStore.setAmounts(stockBillItem.getAmounts());
                    goodsStoreMapper.insert(newGoodsStore);
                }else {//如果不为空则已经存在了直接加库存就可以了
                    goodsStore.setAmounts(goodsStore.getAmounts() + stockBillItem.getAmounts());
                    goodsStoreMapper.updateByPrimaryKey(goodsStore);
                }
            }
        }
        stockBillMapper.changeStatus(stockBill.getId(),StockBill.BILLSTATUS_CANCELLATION);
    }

    @Override
    @Transactional
    public void putStoreBill(Object putStoreBill) throws ParseException {
        //获取当前订单数据
        List list = (List) putStoreBill;
        LinkedHashMap map = (LinkedHashMap)list.get(0);
        System.out.println(map);
        StockBill stockBill = new StockBill();
        stockBill.setType((Integer) map.get("type"));
        stockBill.setStoreId((String) map.get("storeId"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        stockBill.setBusiDate(simpleDateFormat.parse((String) map.get("busiDate")));
        stockBill.setRemark((String)map.get("remark"));
        stockBill.setStatus(StockBill.BILLSTATUS_NORMAL);
        stockBill.setOperateDate(new Date());
        stockBill.setOperatorId(ShiroUtils.getUser().getId());
        stockBillMapper.insert(stockBill);
        //将数据插入到中间表中
        List stockBillItems = (List) list.get(1);
        for (Object stockBillItem : stockBillItems) {
            LinkedHashMap stockBillItemMap = (LinkedHashMap) stockBillItem;
            StockBillItem newStockBillItem1 = new StockBillItem();
            newStockBillItem1.setGoodsId(stockBillItemMap.get("goodsId")+"");
            newStockBillItem1.setPrice(new BigDecimal((String) stockBillItemMap.get("price")));
            newStockBillItem1.setAmounts(Integer.parseInt(stockBillItemMap.get("amounts")+"") );
            newStockBillItem1.setState(false);
            newStockBillItem1.setBillId(stockBill.getId()+"");
            stockBillItemMapper.insert(newStockBillItem1);

            GoodsStore goodsStore = goodsStoreMapper.selectByGoods(newStockBillItem1.getGoodsId(), stockBill.getStoreId());
            //判断仓库中是否已经存在该商品了
            if (goodsStore==null){
                GoodsStore newGoodsStore = new GoodsStore();
                newGoodsStore.setGoodsId(newStockBillItem1.getGoodsId());
                newGoodsStore.setStoreId(stockBill.getStoreId());
                newGoodsStore.setAmounts(newStockBillItem1.getAmounts());
                goodsStoreMapper.insert(newGoodsStore);
            }else {
                goodsStore.setAmounts(goodsStore.getAmounts()+newStockBillItem1.getAmounts());
                goodsStoreMapper.updateByPrimaryKey(goodsStore);
            }

        }

    }

    @Override
    @Transactional
    public void outStoreBill(Object outStoreBill) throws ParseException {
        //获取当前订单数据
        List list = (List) outStoreBill;
        LinkedHashMap map = (LinkedHashMap)list.get(0);
        System.out.println(map);
        StockBill stockBill = new StockBill();
        stockBill.setType((Integer) map.get("type"));
        stockBill.setStoreId((String) map.get("storeId"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        stockBill.setBusiDate(simpleDateFormat.parse((String) map.get("busiDate")));
        stockBill.setRemark((String)map.get("remark"));
        stockBill.setStatus(StockBill.BILLSTATUS_NORMAL);
        stockBill.setOperateDate(new Date());
        stockBill.setOperatorId(ShiroUtils.getUser().getId());
        stockBillMapper.insert(stockBill);
        //将数据插入到中间表中
        List stockBillItems = (List) list.get(1);
        for (Object stockBillItem : stockBillItems) {
            LinkedHashMap stockBillItemMap = (LinkedHashMap) stockBillItem;
            StockBillItem newStockBillItem1 = new StockBillItem();
            newStockBillItem1.setGoodsId(stockBillItemMap.get("goodsId")+"");
            newStockBillItem1.setPrice(new BigDecimal((String) stockBillItemMap.get("price")));
            newStockBillItem1.setAmounts(Integer.parseInt(stockBillItemMap.get("amounts")+"") );
            newStockBillItem1.setState(false);
            newStockBillItem1.setBillId(stockBill.getId()+"");
            stockBillItemMapper.insert(newStockBillItem1);

            GoodsStore goodsStore = goodsStoreMapper.selectByGoods(newStockBillItem1.getGoodsId(), stockBill.getStoreId());
            //判断仓库中是否已经存在该商品了
            if (goodsStore==null){
                throw new BusinessException("仓库没有该物品,不可出库,非法操作");
            }else {
                if (goodsStore.getAmounts()>=newStockBillItem1.getAmounts()){
                    goodsStore.setAmounts(goodsStore.getAmounts()-newStockBillItem1.getAmounts());
                    goodsStoreMapper.updateByPrimaryKey(goodsStore);
                }else {
                    throw new BusinessException("仓库库存不足,不可出库,非法操作");
                }
            }
        }

    }

    @Override
    public List<StockBill> selectAll() {
        return stockBillMapper.selectAll();
    }
}
